<template>
	<u-upload :fileList="fileList" @afterRead="afterRead" name="tx" :maxCount="1" :deletable='false'
		:maxSize="1*1024*1024" :previewImage="true" :previewFullImage='false'>
		<u-avatar :src="pic" size="80"></u-avatar>
	</u-upload>
</template>

<script>
	let access_token, userinfo,_this,ossKey;
	export default {
		name: "ossUploadPic",
		data() {
			return {
				fileList: [],
				pic: ''
			};
		},
		methods: {
			async afterRead(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式		
				let lists = [].concat(event.file); //concat用于数组合并
				//let fileListLen = this.fileList.length;
				lists.map((item) => {
					this['fileList'].push({
						...item,
						status: 'uploading',
						message: '上传中……'
					})
				})
				/* let a = [1,2,3]; //...展开/收集运算符
				let b = [0,...a,4];//[0,1,2,3,4]
				let a = [1,2,3];
				let [b,...c] = a ; //b=1，c=[2,3] */

				//for (let i = 0; i < lists.length; i++) {
				//条件编译
				// #ifdef H5
				const filename = lists[0].name;
				// #endif
				// #ifndef H5
				const filename = lists[0].thumb;
				// #endif
				//接下来判断文件扩展名是否正确
				const ext = filename.slice(filename.lastIndexOf('.'))
			.toLowerCase(); //slice用于返回数组（字符串）中指定起始值至结束值之间元素（内容），如果没有给结束值，就返回起始值以后的所有内容
				const allowExt = ['.jpg', '.jpeg', '.png', '.gif'];
				if (allowExt.indexOf(ext) == -1) {
					//说明扩展名不对
					uni.$u.toast('只能上传 ' + allowExt.join('、') + ' 文件');
					this.fileList.pop();
					return;
				}
				try{
					const result = await this.uploadFilePromise(lists[0].url,ext); //返回的是上传成功远程文件名
					if(result){ 
						//上传成功后，后台返回空。否则，返回具体的错误信息
						uni.$u.toast('上传头像出错1');
						return;
					}
					//到这里表示上传OK，还需要更新头像。
					await uni.$u.http.post('/api/user/avatar',{
						avatar:ossKey
					},{
						header:{
							Authorization: 'bearer ' + access_token
						}
					})
					let item = this[`fileList`][0];
					this[`fileList`].splice(0, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: _this.staticServer + ossKey
					}))
					//更新缓存
					let info = uni.getStorageSync('userinfo');
					info.avatar_url = _this.staticServer + ossKey
					uni.setStorageSync('userinfo',info);
					this.pic = _this.staticServer + ossKey;
					//删除fileList，以便可以点击头像继续上传新的头像
					this.fileList.pop();
				}
				catch(e){
					console.log(e);
					uni.$u.toast('上传头像出错2');
					return;
				}
				
				//fileListLen++
				//}
			},
			uploadFilePromise(url,ext) {
				return new Promise(async (resolve, reject) => {
					//首先，通过接口/api/auth/oss/token获取OSS Token。这个Token用于阿里云文件上传。
					let res = await uni.$u.http.get('/api/auth/oss/token', {
						header: {
							Authorization: 'bearer ' + access_token
						}
					})
					ossKey = uni.$u.guid(10) + ext;
					let a = uni.uploadFile({
						url: res.host,
						filePath: url,
						name: 'file',
						formData: {
							'key': ossKey,
							'policy': res.policy,
							'OSSAccessKeyId': res.accessid,
							'success_action_status': '200', //让服务端返回200,不然，默认会返回204
							'signature': res.signature,
						},
						success: (res1) => {
							console.log(res1);
							resolve(res1.data);
						},
						error:(e)=>{
							reject(e);
						}
						
					});
				})
			},
		},
		created() {
			_this = this;
			access_token = uni.getStorageSync('access_token');
			userinfo = uni.getStorageSync('userinfo');
			this.pic = userinfo.avatar_url;
		}
	}
</script>

<style>

</style>
